<?php

namespace app\adminapi\controller;

use app\common\controller\AdminApi;
use think\Cookie;
use think\Hook;

/**
 * 会员接口
 */
class Admin extends AdminApi
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        $auth = $this->auth;

        //监听登录、注册的事件
        Hook::add('admin_login_successed', function ($admin) use ($auth) {
            $postData = json_decode(request()->getContent(), true);
            $rememberPass = $postData['rememberPass'];
            $expire = $rememberPass ? 30 * 86400 : 0;
            if(!empty($expire))
            {
                Cookie::set('admin_id', $admin->id, $expire);
                Cookie::set('admin_token', $auth->getToken(), $expire);
            }
        });

        Hook::add('admin_logout_successed', function ($admin) use ($auth) {
            Cookie::delete('admin_id');
            Cookie::delete('admin_token');
        });
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $postData = json_decode(request()->getContent(), true);

        // 数据验证
        $result = $this->validate($postData, 'Login');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $ret = $this->auth->login($postData['username'], $postData['password']);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getAdminInfo()];
            $this->success('登录成功', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success('登出成功');
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function changepwd()
    {
        $postData = json_decode(request()->getContent(), true);
        $postData['admin'] = $this->auth->getAdminInfo();
        $postData['ip'] = request()->ip();

        // 数据验证
        $result = $this->validate($postData, 'Changepwd');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $ret = $this->auth->changepwd($postData['newpassword']);
        if ($ret) {
            $this->success('密码修改成功');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户列表
     */
    public function list()
    {
        $postData = json_decode(request()->getContent(), true);

        // 数据验证
        $result = $this->validate($postData, 'AdminList');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $data = \app\common\model\Admin::getList($postData);
        $this->success('查询成功', $data);
    }

}
